package com.leectrl.controller;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.entity.NormalSerialCode;
import com.hdl.school.utils.TimeUtil;
import com.leectrl.bean.ZigbeeDevice;
import com.leectrl.utils.Bus;
import com.leectrl.utils.DbUtil;
import com.leectrl.utils.RequestBody;
import com.leectrl.utils.RequestMapping;
import com.leectrl.utils.ResponseUtil;
import com.leectrl.utils.StorageManager;

import org.xutils.ex.DbException;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

public class ZigbeeController {
    private boolean gatewayOnline=false;

    public ZigbeeController(){
      Bus.getInstance().on("gateway-status", new Bus.MessageEvent() {
          @Override
          public void onEvent(String key, Object... message) {
              gatewayOnline= (boolean) message[0];
              Log.e("TCP", "网关状态:" + gatewayOnline);

          }
      });
    }

    @RequestMapping(uri = "/app/iot/gateway/info/load", method = "GET", auth = false)
    public JSONObject loadGatewayInfo(@RequestBody JSONObject json) {
        String gatewayIp=StorageManager.getInstance().getItem("gatewayIp");
        if(gatewayIp==null){
            gatewayIp="未配置IP地址";
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("ip",gatewayIp);
        jsonObject.put("on",gatewayOnline);
        return ResponseUtil.responseSuccessMsg(jsonObject);
    }

    @RequestMapping(uri = "/iot/zigbee/device/list", method = "POST", auth = false)
    public JSONObject loadZigbeeDeviceList(@RequestBody JSONObject json) {
        try {
            long count=DbUtil.getInstance().selector(ZigbeeDevice.class).count();
            List<ZigbeeDevice> zigbeeDevices=DbUtil.getInstance().selector(ZigbeeDevice.class).findAll();
            JSONArray jsonArray=new JSONArray();
            if(zigbeeDevices!=null){
                for(ZigbeeDevice zigbeeDevice:zigbeeDevices){
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("tags",zigbeeDevice.getDeviceName());
                    String deviceType=zigbeeDevice.getDeviceType();
                    String typeStr=null;
                    if("zigbee-curtain".equals(deviceType)){
                        typeStr="窗帘电机";
                    }else  if("airctrl-zigbee-leectrl".equals(deviceType)||"zigbee-airctrl".equals(deviceType)){
                        typeStr="空调控制器";
                    }else if(deviceType.startsWith("zigbee-switcher")){
                        typeStr="智能开关";
                    }else{
                        typeStr=deviceType;
                    }
                    jsonObject.put("type_str",typeStr);
                    jsonObject.put("dev_key",zigbeeDevice.getDevicekey());
                    jsonObject.put("mac",zigbeeDevice.getMac());
                    jsonObject.put("update_time", TimeUtil.date2String(zigbeeDevice.getCreateTime()));
                    jsonArray.add(jsonObject);
                }
            }

            return ResponseUtil.responseSuccessTableList( jsonArray,count);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ResponseUtil.responseFailureMsg(-2, "暂无Zigbee设备");
    }

    @RequestMapping(uri = "/app/iot/gateway/white/ip/config", method = "POST", auth = true)
    public JSONObject configWhiteIp(@RequestBody JSONObject json) {
        StorageManager.getInstance().setItem("gatewayIp",json.getString("ip"));
        Bus.getInstance().emit("restart_tcp");
        return ResponseUtil.responseSuccessMsg();
    }


    @RequestMapping(uri = "/api/device/ctrl", method = "POST", auth = true)
    public JSONObject sendControllCmd(@RequestBody JSONObject json) {
        //Bus.getInstance().emit("zigbee_code", "aa");
        return ResponseUtil.responseSuccessMsg();
    }


    @RequestMapping(uri = "/app/iot/gateway/join", method = "POST", auth = true)
    public JSONObject reqJoinGateway(@RequestBody JSONObject json) {
        List<String> code = new ArrayList<>();
        code.add("5c12");
        code.add("07");
        code.add("78");
        code.add("w");
        NormalSerialCode normalSerialCode = new NormalSerialCode();
        normalSerialCode.setName("设备入网");
        normalSerialCode.setCode(code);
        Bus.getInstance().emit("zigbee_code", null, normalSerialCode);
        return ResponseUtil.responseSuccessMsg();
    }

    
    @RequestMapping(uri = "/app/iot/zigbee/device/del", method = "POST", auth = true)
    public JSONObject deleteZigbeeDev(@RequestBody JSONObject json) {
        if(!json.containsKey("mac")){
            return ResponseUtil.responseFailureMsg(-2,"缺少必要参数");
        }
        try {
            ZigbeeDevice zigbeeDevice=DbUtil.getInstance().selector(ZigbeeDevice.class).where("mac","=",json.getString("mac")).findFirst();
            DbUtil.getInstance().delete(zigbeeDevice);
            Bus.getInstance().emit("zigbee_dev_event","del",zigbeeDevice);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ResponseUtil.responseSuccessMsg();
    }


    @RequestMapping(uri = "/app/iot/zigbee/device/save", method = "POST", auth = true)
    public JSONObject saveZigbeeDeviceInfo(@RequestBody JSONObject json) {
        String mac=json.getString("mac");
        String devType=json.getString("dev_type");
        if(TextUtils.isEmpty(mac)||TextUtils.isEmpty(devType)){
            return ResponseUtil.responseFailureMsg(-2,"缺少必要参数");
        }
        if(!json.containsKey("checkedLine")){
            return ResponseUtil.responseFailureMsg(-2,"缺少必要参数");
        }
        JSONArray checkedLine=json.getJSONArray("checkedLine");
        ZigbeeDevice zigbeeDevice=new ZigbeeDevice();
        zigbeeDevice.setMac(mac);
        zigbeeDevice.setDeviceType(devType);
        StringBuffer keyBuffer=new StringBuffer();
        StringBuffer nameBuffer=new StringBuffer();
        StringBuffer enableBuffer=new StringBuffer();
        for(int i=0;i<checkedLine.size();i++){
            JSONObject line=checkedLine.getJSONObject(i);
            nameBuffer.append(line.getString("title"));
            keyBuffer.append(line.getString("line"));
            enableBuffer.append(line.getString("enable")==null?"1":line.getString("enable"));
            nameBuffer.append(",");
            keyBuffer.append(",");
            enableBuffer.append(",");
        }
        zigbeeDevice.setDeviceName(nameBuffer.substring(0,nameBuffer.length()-1));
        zigbeeDevice.setDevicekey(keyBuffer.substring(0,keyBuffer.length()-1));
        zigbeeDevice.setEnableTag(enableBuffer.substring(0,enableBuffer.length()-1));
        zigbeeDevice.setCreateTime(new Date(System.currentTimeMillis()));
        try {
            DbUtil.getInstance().saveOrUpdate(zigbeeDevice);
        } catch (DbException e) {
            e.printStackTrace();
        }

        Bus.getInstance().emit("zigbee_dev_event","add",zigbeeDevice);
        return ResponseUtil.responseSuccessMsg();
    }
}
